// $Id: common.c 81 2011-04-24 07:37:10Z cedric.shih@gmail.com $
/*
 * Copyright (C) 2011 Cedric Shih <cedric.shih@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

#include <stdlib.h>
#include <string.h>

#include <nio/buffer.h>

#include "niohttp.h"

#include "log.h"

#include "common.h"

int niohttp_version_set(struct niohttp_version *version, const char *string)
{
	return niohttp_version_nset(version, string, strlen(string));
}

int niohttp_version_nset(struct niohttp_version *version,
		const char *string, size_t len)
{
	int rc;
	char *str = NULL, *ptr;
	long value;

	if (!version || !string) {
		niohttp_error("null argument(s)");
		rc = NIOHTTP_EINVAL;
		goto finally;
	}

	niohttp_debug("setting version: %.*s", len, string);

	if (!(str = malloc(len + 1))) {
		niohttp_error("failed to malloc");
		rc = NIOHTTP_ENOMEM;
		goto finally;
	}

	memcpy(str, string, len);
	str[len] = '\0';

	value = strtol(str, &ptr, 10);

	if (ptr == str || value < 0 || *ptr != '.' ||
			*(ptr + 1) == '\0') {
		niohttp_error("invalid version: %s", str);
		rc = NIOHTTP_EINVAL;
		goto finally;
	}

	version->major = value;

	value = strtol(ptr + 1, &ptr, 10);

	if (value < 0 || ptr != (str + len)) {
		rc = NIOHTTP_EINVAL;
		niohttp_error("invalid version: %s", str);
		goto finally;
	}

	version->minor = value;

	if (version->string) {
		free(version->string);
	}

	version->string = str;
	rc = 0;

finally:
	if (rc != 0) {
		if (str) {
			free(str);
		}
	}
	return rc;
}
